﻿using System;
using System.Collections.Generic;
using System.Text;
using WeChat.PlatForm.Entity;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace WeChat.PlatForm.DataAccess.Repository
{
    public class TestRepository
    {
        public void ToTest()
        {
            using (MyDBContext context = new MyDBContext())
            {

                //新增
                //PersonEntity pers = new PersonEntity()
                //{
                //    Name = "苗玉凯",
                //    Age = 18,
                //    School = new SchoolEntity() { Name = "上海交通大学" },
                //};
                //context.Persons.Add(pers);
                //context.SaveChanges();

                //查询Include(产生join，比如School.City，“City”是假设School的导航属性。是对导航属性的导航属性进行递归链接)
                //PersonEntity model = context.Persons.Include("School").Include("School.City").AsNoTracking().FirstOrDefault();
                //PersonEntity model = context.Persons.Include(a => a.School).AsNoTracking().FirstOrDefault();
                //string name = model.School.Name;

                //如果想用查询的实体关联别的表，那么就不要使用AsNoTracking解除EF的管理
                RoleEntity role = context.Roles.Where(a => a.NAME == "书房管理员").FirstOrDefault();

                //把琉游离态改成未改变状态
                //EntityState Oldstas = context.Entry(role).State;
                //context.Roles.Attach(role);
                //EntityState Newstas = context.Entry(role).State;

                //新增 多对多拆分成一个中间表进行关联
                UserRoleEntity pers = new UserRoleEntity()
                {
                    Role = role,  //new RoleEntity() { NAME = "新角色" },
                    User = new UserEntity() { Name = "仅仅比较帅" }
                };
                context.UserRoles.Add(pers);
                context.SaveChanges();

                //查询关系集合
                //List<UserRoleEntity> roleUser = context.UserRoles.Include(a => a.User).Include(a => a.Role).ToList();
            }
        }
    }
}
